package nl.saxion.act.bus;

import nl.saxion.act.gameframework.Actor;
import nl.saxion.act.gameframework.World;
import nl.saxion.act.logging.EasyLog;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;

public class Buswereld extends World {
	public enum TILE_TYPES {
		BUS,
		INSTAPPER,
		UITSTAPPER,
		REIZIGER,
		HALTE,
		PLATTEGROND
	}

	private Bitmap    bitmaps[]    = new Bitmap[ TILE_TYPES.values().length ];
	private Route     route;

	public Buswereld( Resources r, BuschauffeurFactoryInterface factory  ) {
		super( new Rect( -1224, -417, 2756-1224, 1968-417 ), new BuswereldLevelGenerator( factory ), 1 );
		route = new Route( r );
		loadTiles( r );
	}

	public Bitmap getBitmap( TILE_TYPES type ) { return bitmaps[ type.ordinal() ]; }
	public void   readRoute()                  { route.readRoute( this );          }
	public Route  getRoute()                   { return route;                     }
	
	protected boolean isEndOfLevel() {
		return zijnAlleBussenLeeg() && zijnAlleReizigerOpBestemming();
	}

	private boolean zijnAlleBussenLeeg() {
		for ( Actor actor : getAllActiveActorsOfType( BusActor.class ) ) {
			BusActor busActor = (BusActor) actor;
			if ( ! busActor.getBusPassagiers().isEmpty() )
				return true;
		}
		return false;
	}

	private boolean zijnAlleReizigerOpBestemming() {
		for ( Actor actor : getAllPassiveActorsOfType( HalteProxy.class ) ) {
			HalteProxy halte = (HalteProxy) actor;
			for ( Reiziger reiziger : halte.getReizigers() ) {
				if ( ! reiziger.isOpBestemming( halte.getNaam() ) )
					return true;
			}
		}
		return false;
	}

	private void loadTiles( Resources r ) {
		loadTile( TILE_TYPES.BUS,         r.getDrawable( R.drawable.bus        ) );
		loadTile( TILE_TYPES.INSTAPPER,   r.getDrawable( R.drawable.instapper  ) );
		loadTile( TILE_TYPES.UITSTAPPER,  r.getDrawable( R.drawable.uitstapper ) );
		loadTile( TILE_TYPES.HALTE,       r.getDrawable( R.drawable.halte      ) );
		loadTile( TILE_TYPES.REIZIGER,    r.getDrawable( R.drawable.reiziger   ) );
		loadTile( TILE_TYPES.PLATTEGROND, r.getDrawable( R.drawable.map        ) );
	}

	private void loadTile(TILE_TYPES tyleType, Drawable tile ) {
		bitmaps[ tyleType.ordinal() ] = Bitmap.createBitmap( tile.getIntrinsicWidth(), tile.getIntrinsicHeight(), Bitmap.Config.ARGB_8888 );
		Canvas canvas = new Canvas( bitmaps[ tyleType.ordinal() ] );
		tile.setBounds( 0, 0, tile.getIntrinsicWidth() - 1, tile.getIntrinsicHeight() - 1 );
		tile.draw( canvas );
	}

	public void canvasSizeChanged( int width, int height, int oldwidth, int oldheight ) {
		synchronized (this) {
			EasyLog.d( "Buswereld.canvasSizeChanged(" + width + "," + height + ") -> buswereld veranderd zelf niet" );
		}
	}
}
